package com.dyh.quickdemozwei.pipe0823;

public class PipeLine {

    BasePipeNode [] nodes;

    private PipeLine(){

    }

    public static PipeLine from(BasePipeNode... nodes){
        PipeLine pipeLine = new PipeLine();


        for (int i=0;i<nodes.length;i++){
            nodes[i].setIndex(i);
        }

        pipeLine.nodes = nodes;
        return pipeLine;
    }

    public ValueContext work(){
        ValueContext context = new ValueContext();
        context.setOutputs(new Object[nodes.length]);

        for (BasePipeNode node : nodes) {
            Exception ex = null;
            Object output = null;
            if (context.getIndex()==nodes.length)
                break;
            try {
                output = node.work(context);
            } catch (Exception e) {
                ex = e;
                context.setIndex(nodes.length);
            }
            if (ex==null){
                context.getOutputs()[context.getIndex()]=output;
                context.indexInc();
            }
        }

        return context;

    }
    public ValueContext work(Object in){
        ValueContext context = new ValueContext();
        context.setOutputs(new Object[nodes.length]);
        context.setIn(in);

        for (BasePipeNode node : nodes) {
            Exception ex = null;
            Object output = null;
            if (context.getIndex()==nodes.length)
                break;
            try {
                output = node.work(context);
            } catch (Exception e) {
                ex = e;
                context.setIndex(nodes.length);
            }
            if (ex==null){
                context.getOutputs()[context.getIndex()]=output;
                context.indexInc();
            }
        }

        return context;
    }


    public static void main(String[] args) {
        PipeLine pipeLine = PipeLine.from(
                new BasePipeNode() {
                    @Override
                    public Object work(ValueContext valueContext) {

                        return  (int)valueContext.getIn()+1;
                    }
                },
                new BasePipeNode() {
                    @Override
                    public Object work(ValueContext valueContext) {
//                        if (1==1)
//                            throw new RuntimeException();
                        return  getLastInputValue(valueContext,Integer.class)*2;
                    }
                },
                new BasePipeNode() {
                    @Override
                    public Object work(ValueContext valueContext) {

                        return  getLastInputValue(valueContext,Integer.class)+"!";
                    }
                }
        );

        ValueContext valueContext = pipeLine.work(1);

        System.out.println();
    }

}
